#include <SDL/SDL.h>
#include <glib.h>

#include "control.h"
#include "global.h"
#include "sound.h"
#include "errors.h"
#include "screen.h"

#include <deque>

SDL_Joystick* joy = NULL;
extern GMainLoop* loop;
deque<const char*> bgs;

int init_control() {
	/* Check and open joystick device */
	if (SDL_NumJoysticks() > 0) {
		joy = SDL_JoystickOpen(0);
		if(!joy) {
			ELOG("Couldn't open joystick 0: %s", SDL_GetError());
			return ESDL_INIT_INPUT;
		}
	}
	//ELOG("%s", "Control subsystem intialised");

	bgs.push_back("images/bwiiuup_mentok2.jpg");
	bgs.push_back("images/bwiiuup_mentok3.jpg");
	bgs.push_back("images/bwiiuup_mentok.jpg");
	return 0;
}

void kill_control() {
	if (joy) {
		SDL_JoystickClose(joy);
	}
}

gboolean idle_control(gpointer data) {
	SDL_Event event;
	if (SDL_PollEvent(&event)) {
		control_event(event);
	}

	SDL_PumpEvents();
	return TRUE;
}

static void next_bg() {
	const char* bg = bgs.front();
	//ELOG("Background image: %s", bg);
	set_bg(bg);
	bgs.pop_front();
	bgs.push_back(bg);
}

static void key_up_event(SDL_Event ev) {
	switch (ev.key.keysym.sym) {
			case SDLK_ESCAPE:
				g_main_loop_quit(loop);
				break;
			case SDLK_b: {
				next_bg();
				break;
			}
			case SDLK_l: {
				print_tracks();
				break;
			}
			case SDLK_SPACE: {
				play_pause();
				break;
			}
			case SDLK_LEFTBRACKET: {
				prev_track();
				break;
			}
			case SDLK_RIGHTBRACKET: {
				next_track();
				break;
			}
			default: break;
	}
}

static void joyb_event(SDL_Event ev) {
	static unsigned long buttonDown = 0;
	if (ev.jbutton.button >= VK_MAX) {
		return;
	}
	if (ev.type == SDL_JOYBUTTONDOWN) {
		buttonDown |= bmask(ev.jbutton.button);
		if (buttonDown & (bmask(VK_FR) | bmask(VK_FL))) {
			// TODO: L + R pressed

			// Buttons can only go up from here!
			// This will prevent the button up events from being processed
			buttonDown &= ~(bmask(VK_FR) | bmask(VK_FL));
			return;
		}
		switch (ev.jbutton.button) {
			case VK_HOME: {
				g_main_loop_quit(loop);
				break;
			}
			case VK_FA: {
				next_bg();
				break;
			}
			case VK_FL: {
				break;
			}
			case VK_FR: {
				break;
			}
			default: break;
		}
	} else if (ev.type == SDL_JOYBUTTONUP) {
		/* Make sure the button was acctually pressed */
		if (buttonDown & bmask(ev.jbutton.button)) {
			buttonDown &= ~bmask(ev.jbutton.button);
			switch (ev.jbutton.button) {
				default: break;
			}
		}
	}
}

void control_event(SDL_Event ev) {
	switch (ev.type) {
		case SDL_QUIT: {
			g_main_loop_quit(loop);
			break;
		}
		case SDL_KEYUP: {
			//ELOG("%s","SDL key up event occurred");
			key_up_event(ev);
			break;
		}
		case SDL_JOYBUTTONDOWN:
			//ELOG("%s","SDL joybutton down event occurred");
		case SDL_JOYBUTTONUP: {
			joyb_event(ev);
		}
		default: break;
	}
}

/* vim:set ts=2 sts=2 sw=2 noexpandtab: */
